import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { RandomEventItem } from './RandomEventItem';
import { RandomEventStage } from './RandomEventStage';
import { RandomEventMission } from './RandomEventMission';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**随机事件管理属性枚举*/
export const enum E_RandomEvent {
	/**快刷次数*/
	QUICK_REFRESH_COUNT = 0,
	/**慢刷次数*/
	SLOW_REFRESH_COUNT = 1,
	/**位置1的事件id*/
	POS_1_EVENT_ID = 2,
	/**位置2的事件id*/
	POS_2_EVENT_ID = 3,
	/**位置3的事件id*/
	POS_3_EVENT_ID = 4,
	/**下次检查时间*/
	NEXT_CHECK_TIME = 7,
	/**事件表*/
	EVENT = 9,
	/**关卡事件信息*/
	STAGE_INFO = 10,
	/**随机任务*/
	RANDOM_MISSION = 11,
	/**枚举数量*/
	EnumCount = 12
}


/**随机事件管理*/
export class RandomEvent {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_RANDOM_EVENT_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_RANDOM_EVENT_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: RandomEvent[] = [];

	/**创建入口*/
	public static create(json?: string): RandomEvent {
		const c = this.POOL.pop() || new RandomEvent();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**快刷次数 (uint16)*/
	protected _quickRefreshCount: number;
	/**慢刷次数 (uint16)*/
	protected _slowRefreshCount: number;
	/**位置1的事件id (uint32)*/
	protected _pos1EventId: number;
	/**位置2的事件id (uint32)*/
	protected _pos2EventId: number;
	/**位置3的事件id (uint32)*/
	protected _pos3EventId: number;
	/**下次检查时间 (long)*/
	protected _nextCheckTime: number;
	/**事件表*/
	protected _event: HashMap<number, RandomEventItem> = null;
	/**关卡事件信息*/
	protected _stageInfo: RandomEventStage = null;
	/**随机任务*/
	protected _randomMission: RandomEventMission = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (RandomEvent.POOL.indexOf(this) === -1) {
			RandomEvent.POOL.push(this);
		}
	}

	/**快刷次数*/
	public get quickRefreshCount() {
		return this._quickRefreshCount;
	}


	/**快刷次数*/
	public set quickRefreshCount(v: number) {
		this._quickRefreshCount = v;
	}


	/**慢刷次数*/
	public get slowRefreshCount() {
		return this._slowRefreshCount;
	}


	/**慢刷次数*/
	public set slowRefreshCount(v: number) {
		this._slowRefreshCount = v;
	}


	/**位置1的事件id*/
	public get pos1EventId() {
		return this._pos1EventId;
	}


	/**位置1的事件id*/
	public set pos1EventId(v: number) {
		this._pos1EventId = v;
	}


	/**位置2的事件id*/
	public get pos2EventId() {
		return this._pos2EventId;
	}


	/**位置2的事件id*/
	public set pos2EventId(v: number) {
		this._pos2EventId = v;
	}


	/**位置3的事件id*/
	public get pos3EventId() {
		return this._pos3EventId;
	}


	/**位置3的事件id*/
	public set pos3EventId(v: number) {
		this._pos3EventId = v;
	}


	/**下次检查时间*/
	public get nextCheckTime() {
		return this._nextCheckTime;
	}


	/**下次检查时间*/
	public set nextCheckTime(v: number) {
		this._nextCheckTime = v;
	}


	/**设置事件表*/
	public putEvent(k: number, v: RandomEventItem): RandomEventItem {
		const ov = this._event.put(k, v);
		return ov;
	}


	/**获取事件表*/
	public getEvent(k: number) {
		return this._event.get(k);
	}


	/**删除事件表*/
	public removeEvent(k: number, autoDestroy = false): RandomEventItem {
		const ov = this._event.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取事件表映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getEventKeys(): number[] {
		return this._event.getKeys();
	}


	/**获取事件表映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getEventValues(): RandomEventItem[] {
		return this._event.getValues();
	}


	/**清空事件表映射表*/
	public clearEventMap(autoDestroy = false): void {
		const ks = this._event.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeEvent(ks[i], autoDestroy);
		}
	}


	/**关卡事件信息*/
	public get stageInfo() {
		return this._stageInfo;
	}


	/**随机任务*/
	public get randomMission() {
		return this._randomMission;
	}



	/**通过枚举获取值*/
	public getV(k: E_RandomEvent): any {
		switch (k) {
			case E_RandomEvent.QUICK_REFRESH_COUNT: return this._quickRefreshCount;
			case E_RandomEvent.SLOW_REFRESH_COUNT: return this._slowRefreshCount;
			case E_RandomEvent.POS_1_EVENT_ID: return this._pos1EventId;
			case E_RandomEvent.POS_2_EVENT_ID: return this._pos2EventId;
			case E_RandomEvent.POS_3_EVENT_ID: return this._pos3EventId;
			case E_RandomEvent.NEXT_CHECK_TIME: return this._nextCheckTime;
			case E_RandomEvent.EVENT: return this._event;
			case E_RandomEvent.STAGE_INFO: return this._stageInfo;
			case E_RandomEvent.RANDOM_MISSION: return this._randomMission;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_RandomEvent, v: any): void {
		switch (k) {
			case E_RandomEvent.QUICK_REFRESH_COUNT: this._quickRefreshCount = v; break;
			case E_RandomEvent.SLOW_REFRESH_COUNT: this._slowRefreshCount = v; break;
			case E_RandomEvent.POS_1_EVENT_ID: this._pos1EventId = v; break;
			case E_RandomEvent.POS_2_EVENT_ID: this._pos2EventId = v; break;
			case E_RandomEvent.POS_3_EVENT_ID: this._pos3EventId = v; break;
			case E_RandomEvent.NEXT_CHECK_TIME: this._nextCheckTime = v; break;
			case E_RandomEvent.EVENT: this._event = v; break;
			case E_RandomEvent.STAGE_INFO: this._stageInfo = v; break;
			case E_RandomEvent.RANDOM_MISSION: this._randomMission = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//快刷次数
		this._quickRefreshCount = 0;
		//慢刷次数
		this._slowRefreshCount = 0;
		//位置1的事件id
		this._pos1EventId = 0;
		//位置2的事件id
		this._pos2EventId = 0;
		//位置3的事件id
		this._pos3EventId = 0;
		//下次检查时间
		this._nextCheckTime = 0;
		//事件表
		if (this._event) {
			const list = this._event.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._event.clear();
		}
		else {
			this._event = new HashMap<number, RandomEventItem>();
		}
		//关卡事件信息
		if (this._stageInfo) {
			this._stageInfo.destroy();
			this._stageInfo = null;
		}
		if (!fromDestroy) {
			this._stageInfo = RandomEventStage.create();
		}
		//随机任务
		if (this._randomMission) {
			this._randomMission.destroy();
			this._randomMission = null;
		}
		if (!fromDestroy) {
			this._randomMission = RandomEventMission.create();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._quickRefreshCount) {
			json.quickRefreshCount = this._quickRefreshCount;
		}
		if (this._slowRefreshCount) {
			json.slowRefreshCount = this._slowRefreshCount;
		}
		if (this._pos1EventId) {
			json.pos1EventId = this._pos1EventId;
		}
		if (this._pos2EventId) {
			json.pos2EventId = this._pos2EventId;
		}
		if (this._pos3EventId) {
			json.pos3EventId = this._pos3EventId;
		}
		if (this._nextCheckTime) {
			json.nextCheckTime = this._nextCheckTime;
		}
		if (this._event.size() > 0) {
			const ks = this._event.getKeys();
			const vs = this._event.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.event = [ks, list];
		}
		if (this._stageInfo) {
			json.stageInfo = this._stageInfo.stringify(false);
		}
		if (this._randomMission) {
			json.randomMission = this._randomMission.stringify(false);
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.quickRefreshCount) {
			this._quickRefreshCount = json.quickRefreshCount;
		}
		if (json.slowRefreshCount) {
			this._slowRefreshCount = json.slowRefreshCount;
		}
		if (json.pos1EventId) {
			this._pos1EventId = json.pos1EventId;
		}
		if (json.pos2EventId) {
			this._pos2EventId = json.pos2EventId;
		}
		if (json.pos3EventId) {
			this._pos3EventId = json.pos3EventId;
		}
		if (json.nextCheckTime) {
			this._nextCheckTime = json.nextCheckTime;
		}
		if (json.event) {
			const ks: number[] = json.event[0] || (json.event.getKeys ? json.event.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.event[1] || (json.event.getValues ? json.event.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._event.put(ks[i], RandomEventItem.create(vs[i]));
				}
			}
		}
		if (json.stageInfo) {
			this._stageInfo.destroy();
			this._stageInfo = RandomEventStage.create(json.stageInfo);
		}
		if (json.randomMission) {
			this._randomMission.destroy();
			this._randomMission = RandomEventMission.create(json.randomMission);
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint16(this._quickRefreshCount);
		byte.writeUint16(this._slowRefreshCount);
		byte.writeUint32(this._pos1EventId);
		byte.writeUint32(this._pos2EventId);
		byte.writeUint32(this._pos3EventId);
		byte.writeLongNumber(this._nextCheckTime);
		//事件表
		{
			const ks = this._event.getKeys();
			const vs = this._event.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
		this._stageInfo.toBytes(byte);
		this._randomMission.toBytes(byte);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._quickRefreshCount = byte.readUint16();
		this._slowRefreshCount = byte.readUint16();
		this._pos1EventId = byte.readUint32();
		this._pos2EventId = byte.readUint32();
		this._pos3EventId = byte.readUint32();
		this._nextCheckTime = byte.readLongNumber();
		//事件表
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = RandomEventItem.create();
				v.fromBytes(byte);
				this._event.put(k, v);
			}
		}
		this._stageInfo.fromBytes(byte);
		this._randomMission.fromBytes(byte);
		return this;
	}


	/**克隆*/
	public clone(): RandomEvent {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = RandomEvent.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = RandomEvent.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//快刷次数
			if (idx === E_RandomEvent.QUICK_REFRESH_COUNT) {
				const oldv = this._quickRefreshCount;
				this._quickRefreshCount = us[i + 1];
				IAsync.dispatch(eventID, idx, this._quickRefreshCount, oldv);
				i += 2;
				continue;
			}
			//慢刷次数
			if (idx === E_RandomEvent.SLOW_REFRESH_COUNT) {
				const oldv = this._slowRefreshCount;
				this._slowRefreshCount = us[i + 1];
				IAsync.dispatch(eventID, idx, this._slowRefreshCount, oldv);
				i += 2;
				continue;
			}
			//位置1的事件id
			if (idx === E_RandomEvent.POS_1_EVENT_ID) {
				const oldv = this._pos1EventId;
				this._pos1EventId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._pos1EventId, oldv);
				i += 2;
				continue;
			}
			//位置2的事件id
			if (idx === E_RandomEvent.POS_2_EVENT_ID) {
				const oldv = this._pos2EventId;
				this._pos2EventId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._pos2EventId, oldv);
				i += 2;
				continue;
			}
			//位置3的事件id
			if (idx === E_RandomEvent.POS_3_EVENT_ID) {
				const oldv = this._pos3EventId;
				this._pos3EventId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._pos3EventId, oldv);
				i += 2;
				continue;
			}
			//下次检查时间
			if (idx === E_RandomEvent.NEXT_CHECK_TIME) {
				const oldv = this._nextCheckTime;
				this._nextCheckTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._nextCheckTime, oldv);
				i += 2;
				continue;
			}

			//事件表
			if (idx === E_RandomEvent.EVENT) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeEvent(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = RandomEventItem.create(us[i + 3]);
					const oldv = this.putEvent(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getEvent(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('RandomEvent RandomEventItem is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}
			//关卡事件信息
			if (idx === E_RandomEvent.STAGE_INFO) {
				const fui: string = us[i + 1];
				if (this._stageInfo) {
					this._stageInfo.processUpdate(fui);
				}
				else {
					console.error('RandomEvent stageInfo is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}
			//随机任务
			if (idx === E_RandomEvent.RANDOM_MISSION) {
				const fui: string = us[i + 1];
				if (this._randomMission) {
					this._randomMission.processUpdate(fui);
				}
				else {
					console.error('RandomEvent randomMission is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in RandomEvent with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: RandomEvent): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._quickRefreshCount !== other._quickRefreshCount) {
			updates.push(E_RandomEvent.QUICK_REFRESH_COUNT, this._quickRefreshCount);
		}
		if (this._slowRefreshCount !== other._slowRefreshCount) {
			updates.push(E_RandomEvent.SLOW_REFRESH_COUNT, this._slowRefreshCount);
		}
		if (this._pos1EventId !== other._pos1EventId) {
			updates.push(E_RandomEvent.POS_1_EVENT_ID, this._pos1EventId);
		}
		if (this._pos2EventId !== other._pos2EventId) {
			updates.push(E_RandomEvent.POS_2_EVENT_ID, this._pos2EventId);
		}
		if (this._pos3EventId !== other._pos3EventId) {
			updates.push(E_RandomEvent.POS_3_EVENT_ID, this._pos3EventId);
		}
		if (this._nextCheckTime !== other._nextCheckTime) {
			updates.push(E_RandomEvent.NEXT_CHECK_TIME, this._nextCheckTime);
		}

		//事件表
		{
			const idx = E_RandomEvent.EVENT;
			const ks1 = this._event.getKeys();
			const ks2 = other._event.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getEvent(k);
					const oldv = other.getEvent(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getEvent(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}
		//关卡事件信息
		{
			const ui = this._stageInfo.getCompareInfo(other._stageInfo);
			if (ui && ui.length > 0) {
				updates.push(E_RandomEvent.STAGE_INFO, ui);
			}
		}
		//随机任务
		{
			const ui = this._randomMission.getCompareInfo(other._randomMission);
			if (ui && ui.length > 0) {
				updates.push(E_RandomEvent.RANDOM_MISSION, ui);
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(RandomEvent.TOTAL_EVENT_ID, this.getV(0));
	}

}
